package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mappers.DishMapper;
import com.itheima.reggie.mappers.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {

        /**
         * 通过user_id与dish_id或setmeal_id查询购物车表是否有该购物项，
         * 如果没有就插入数据，有则更新数量
         */
        ShoppingCart shoppingCartOne = shoppingCartMapper.findUidAndDidOrSid(shoppingCart);

        if (shoppingCartOne == null) {
            shoppingCart.setCreateTime(LocalDateTime.now());
            //每次添加都是一份
            shoppingCart.setNumber(1);

            shoppingCartMapper.add(shoppingCart);
        }else {
            shoppingCartOne.setNumber(shoppingCartOne.getNumber()+1);
            shoppingCartMapper.update(shoppingCartOne);
            shoppingCart=shoppingCartOne;
        }


        return shoppingCart;
    }

    @Override
    public R<List<ShoppingCart>> findAll(Long userId) {

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findAll(userId);
        return R.success(shoppingCartList);
    }

    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        /**
         * 通过user_id与dish_id或setmeal_id查询购物车表该购物项数量是否大于1，
         * 如果大于1就更新数量，等于1就直接删减
         */
        shoppingCart = shoppingCartMapper.findUidAndDidOrSid(shoppingCart);
        if (shoppingCart.getNumber() == 1) {
            shoppingCartMapper.delete(shoppingCart);
            shoppingCart.setNumber(0);
        } else {
            shoppingCart.setNumber(shoppingCart.getNumber()-1);
            shoppingCartMapper.update(shoppingCart);
        }

        return shoppingCart;
    }

    @Override
    public void clean(Long userId) {
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        shoppingCartMapper.delete(shoppingCart);
    }
}
